package com.xpec.cipher.tals.record;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

import com.xpec.cipher.tals.TalsConstance;
import com.xpec.cipher.tals.Util;

public abstract class TalsRecord
{
	final int headLength = TalsConstance.UINT32_SIZE + TalsConstance.BYTE_SIZE;
	
	public ChannelBuffer resolve()
	{
		int totalLength = headLength + getContentLength();

		// 这种回复是不需要协议结构的，直接发内容。
		if (TalsConstance.CONTENT_TYPE_FLASH_RESPONSE == getContentType())
		{
			return ChannelBuffers.wrappedBuffer(resolveSubStruct());
		}
		else
		{
			byte[] lengthBuffer = Util.transIntegerToByteArray(totalLength);
			byte[] buffer = new byte[headLength];
			for (int i = 0; i < TalsConstance.UINT32_SIZE; i++)
			{
				buffer[i] = lengthBuffer[i];
			}
			buffer[TalsConstance.UINT32_SIZE] = getContentType();
			
			ChannelBuffer buf1 = ChannelBuffers.wrappedBuffer(buffer);
			ChannelBuffer buf2 = resolveSubStruct();
			
			return ChannelBuffers.wrappedBuffer(buf1,buf2);
		}
	}

	protected abstract byte getContentType();

	protected abstract int getContentLength();

	protected abstract ChannelBuffer resolveSubStruct();
}
